package com.backend.controller.rbac;

import com.backend.annotation.RequireAuth;
import com.backend.annotation.RequireRole;
import com.backend.service.rbac.RoleAuthService;
import com.common.constant.MessageConstant;
import com.common.exception.RoleException;
import com.common.result.Result;
import com.pojo.vo.AuthVO;
import com.pojo.vo.RoleAuthVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/roleAuth")
public class RoleAuthController {
    @Autowired
    RoleAuthService roleAuthService;
    /**
     * 通过角色id查询，该角色拥有的所有权限
     */
    @GetMapping("/getAuthByRoleId/{id}")
    @RequireRole("admin")
    @RequireAuth("common")
    public Result getAuthByRoleId(@PathVariable("id") Long id) {
        List<AuthVO> roleAuthVO = roleAuthService.getAuthsByRoleId(id);
        return Result.success(roleAuthVO);
    }
    /**
     * 通过角色id，删除某角色拥有的所有权限
     */
    @DeleteMapping("/removeAuthsByRoleId/{id}")
    @RequireRole("admin")
    public Result removeAuthsByRoleId(@PathVariable("id") Long id) {
        Integer result = roleAuthService.removeAuthsByRoleId(id);
        if (result == 0) {
            return Result.error(MessageConstant.ROLE_AUTH_DELETE_FAIL);
        }
        return Result.success(MessageConstant.ROLE_AUTH_DELETE_SUCCESS);
    }
    /**
     * 通过角色id重新分配某个角色拥有的所有权限
     */
    @PutMapping("/updateAuthByRoleId/{id}")
    @RequireRole("admin")
    public Result updateAuthByRoleId(@PathVariable("id") Long id,  @RequestBody List<Long> authIds) {
        roleAuthService.removeAuthsByRoleId(id);
        Integer result = roleAuthService.updateAuthByRoleId(id, authIds);
        if (result == 0) {
            return Result.error(MessageConstant.ADD_ROLE_AUTH_FAIL);
        }
        return Result.success(MessageConstant.ADD_ROLE_AUTH_SUCCESS);
    }
}